<template>
    <van-address-list :list="adressList" default-tag-text="默认" @add="onAdd" @edit="onEdit"
        :add-button-text="route.query.isCart === '1' || route.query.goodsId ? '生成订单' : '新增地址'"
        v-model="checkedAddress" />
</template>

<script setup>
import { onMounted, ref } from "vue";
import { getAddressList } from "@/api/address";
import { useRouter, useRoute } from 'vue-router'

let router = useRouter()
let route = useRoute()

let checkedAddress = ref(null)
// 地址列表
let adressList = ref([]);
// 进入页面 获取数据
onMounted(async () => {

    // 获取地址列表
    let arr = (await getAddressList({ limit: 100, page: 1 })).data.list;
    console.log(arr);
    //   把 后端 数据 构造为组件 接受的数据
    adressList.value = arr.map((item) => {
        return {
            id: item.id,
            name: item.name,
            tel: item.phone,
            address: item.province + item.city + item.town + item.detail,
            isDefault: item.is_default === 1
        };
    });
    //找出默认地址
    let defaultAddress = adressList.value.find(item =>
        item.isDefault === true
    )
    checkedAddress.value = defaultAddress.id
});

// 点击新增 跳转至新增
//判断是新增地址还是生成订单
let onAdd = () => { 
    // 判断是新增地址  还是 生成订单
    if (route.query.isCart) {
        // 从购物车 来的  点击跳转至 生成订单页面
        router.push(`/create-order?checkedGoods=${route.query.checkedGoods}&addressId=${checkedAddress.value}`)
        // 
    } else if (route.query.goodsId) {
        // 从 商品详情直接购买的   传递商品id
        router.push(`/create-order?addressId=${checkedAddress.value}&goodsId=${route.query.goodsId}`)
    } else {
        router.push('/edit-address')
    }

}
//点击编辑
let onEdit = (item) => {
    router.push(`/edit-address?id=${item.id}`)
}



</script>